﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebUI
{
    /// <summary>
    /// Json数据绑定类 对json数据反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class JsonBinder<T> : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //从请求中获取提交的参数数据 
            var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;
            //提交参数是对象 
            if (json.StartsWith("{") && json.EndsWith("}"))
            {
                JObject jsonBody = JObject.Parse(json);
                JsonSerializer js = new JsonSerializer();
                object obj = js.Deserialize(jsonBody.CreateReader(), typeof(T));
                return obj;
            }
            //提交参数是数组 
            if (json.StartsWith("[") && json.EndsWith("]"))
            {
                IList<T> list = new List<T>();
                JArray jsonRsp = JArray.Parse(json);
                if (jsonRsp != null)
                {
                    for (int i = 0; i < jsonRsp.Count; i++)
                    {
                        JsonSerializer js = new JsonSerializer();
                        object obj = js.Deserialize(jsonRsp[i].CreateReader(), typeof(T));
                        list.Add((T)obj);
                    }
                }
                return list;
            }
            return null;
        }
    }
    /// <summary>
    /// DataGrid的data column等json数据绑定类 对json数据反序列化成DataTable
    /// </summary>
    public class DataGridJsonBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //从请求中获取提交的参数数据 
            var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;
            //提交参数是数组 传入的rows和columns都是数组，故不做对象处理
            if (json.StartsWith("[") && json.EndsWith("]"))
            {
                if (json.StartsWith("[[") && json.EndsWith("]]"))
                {
                    //columns
                    json = json.Substring(1);
                    json = json.Substring(0, json.Length - 1);
                    JArray jsonRsp = JArray.Parse(json);
                    DataTable dt = new DataTable();
                    if (jsonRsp != null)
                    {
                        dt = (DataTable)JsonConvert.DeserializeObject<DataTable>(json);
                    }
                    return dt;
                }
                else
                {
                    //rows
                    JArray jsonRsp = JArray.Parse(json);
                    DataTable dt = new DataTable();
                    if (jsonRsp != null)
                    {
                        dt = (DataTable)JsonConvert.DeserializeObject<DataTable>(json);
                    }
                    return dt;
                }
            }
            return null;
        }

        public object GetChildModelFilterNoField(string json)
        {
            JArray jsonRsp = JArray.Parse(json);
            for (int i = 0; i < jsonRsp.Count; i++)
            {

            }
            return jsonRsp;
        }
    }

    public static class JsonHelper
    {
        /// <summary>
        /// 使用Json.Net 序列化数据.
        /// 默认的日期格式:yyyy-MM-dd
        /// 默认的枚举格式：枚举的字符串表示
        /// </summary>
        /// <param name="contorller"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ActionResult JsonEx(object data)
        {
            return new ContentResult { Content = SerializeObjectEx(data), ContentType = "application/json", ContentEncoding = null };
        }
        private static string SerializeObjectEx(object value)
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();//这里使用自定义日期格式，默认是ISO8601格式         
            timeConverter.DateTimeFormat = "yyyy-MM-dd";//设置时间格式 
            Newtonsoft.Json.Converters.StringEnumConverter enumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();//枚举值转换成字符串名字 
            JsonSerializerSettings JsonSetting = new JsonSerializerSettings();
            JsonSetting.Converters.Add(timeConverter);
            JsonSetting.Converters.Add(enumConverter);
            return JsonConvert.SerializeObject(value, JsonSetting);
        }

    }
}